package algotithm.jianzhioffer.test29;

/**
 * @author zhouyanxiang
 * @Date 2020-12-2020/12/29-15:37
 */
public class Solution {

    public static void main(String[] args) {
//        int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
        int[][] matrix = {{2,5,8},{4,0,-1}};
        Solution solution = new Solution();
        int[] nums = solution.spiralOrder(matrix);
        for (int num : nums) {
            System.out.print(num + " ");
        }
    }

    public int[] spiralOrder(int[][] matrix) {
        if (matrix.length == 0 ) {
            return new int[0];
        }
        int t = 0, b = matrix.length - 1;
        int l = 0, r = matrix[0].length - 1;
        int x = 0;
        int[] arr  = new int[(b+1)*(r+1)];
        while (true) {
            // left to right
            for (int i = l; i <= r; i++) {
                arr[x++] = matrix[t][i];
            }
            if (++t > b) {
                break;
            }

            // top to bottom
            for (int i = t; i <= b; i++) {
                arr[x++] = matrix[i][r];
            }
            if (--r < l) {
                break;
            }

            // right to left
            for (int i = r; i >= l; i--) {
                arr[x++] = matrix[b][i];
            }
            if (--b < t) {
                break;
            }

            // bottom to top
            for (int i = b; i >= t; i--) {
                arr[x++] = matrix[i][l];
            }
            if (++l > r) {
                break;
            }
        }
        return arr;
    }


}
